#include "ordercontrolwidget.h"
#include "errorhandler.h"
#include <QMessageBox>
#include <QDateTime>

// SEARCH_DELAY_MS 在头文件中已声明为static const，无需重新定义

OrderControlWidget::OrderControlWidget(QWidget *parent)
    : QWidget(parent)
    , m_mainLayout(nullptr)
    , m_searchGroup(nullptr)
    , m_searchLayout(nullptr)
    , m_searchLineEdit(nullptr)
    , m_statusFilterCombo(nullptr)
    , m_dateRangeCombo(nullptr)
    , m_startDateEdit(nullptr)
    , m_endDateEdit(nullptr)
    , m_searchStatusLabel(nullptr)
    , m_actionGroup(nullptr)
    , m_actionLayout(nullptr)
    , m_startPreparingButton(nullptr)
    , m_completeOrderButton(nullptr)
    , m_cancelOrderButton(nullptr)
    , m_refreshButton(nullptr)
    , m_exportButton(nullptr)
    , m_hasCurrentOrder(false)
    , m_searchDelayTimer(nullptr)
{
    // 创建搜索延迟定时器
    m_searchDelayTimer = new QTimer(this);
    m_searchDelayTimer->setSingleShot(true);
    m_searchDelayTimer->setInterval(SEARCH_DELAY_MS);
    
    setupSearchArea();
    setupActionArea();
    
    // 连接定时器
    connect(m_searchDelayTimer, &QTimer::timeout,
            this, &OrderControlWidget::onSearchDelayTimeout);
    
    // 初始更新按钮状态
    updateActionButtons();
}

OrderControlWidget::~OrderControlWidget()
{
    // Qt会自动清理子对象
}

void OrderControlWidget::setCurrentOrder(const Order& order)
{
    m_currentOrder = order;
    m_hasCurrentOrder = order.isValid();
    updateActionButtons();
    
    if (m_hasCurrentOrder) {
        LOG_INFO(QString("当前订单已设置: %1").arg(order.id), "OrderControlWidget");
    }
}

void OrderControlWidget::clearCurrentOrder()
{
    m_currentOrder = Order();
    m_hasCurrentOrder = false;
    updateActionButtons();
}

void OrderControlWidget::setSearchCriteria(const OrderSearchCriteria& criteria)
{
    m_currentCriteria = criteria;
    
    // 更新搜索控件显示
    if (!criteria.customerName.isEmpty()) {
        m_searchLineEdit->setText(criteria.customerName);
    }
    
    // 更新状态过滤
    if (criteria.status != static_cast<OrderStatus>(-1)) {
        int statusIndex = static_cast<int>(criteria.status) + 1; // +1 因为有"全部"选项
        m_statusFilterCombo->setCurrentIndex(statusIndex);
    }
}

void OrderControlWidget::onSearchTextChanged()
{
    // 重启延迟定时器，实现搜索防抖
    m_searchDelayTimer->stop();
    m_searchDelayTimer->start();
}

void OrderControlWidget::onStatusFilterChanged()
{
    emitSearchCriteriaChanged();
}

void OrderControlWidget::onDateRangeChanged()
{
    int rangeIndex = m_dateRangeCombo->currentIndex();
    
    if (rangeIndex == m_dateRangeCombo->count() - 1) {
        // 自定义日期范围
        m_startDateEdit->show();
        m_endDateEdit->show();
    } else {
        // 预设日期范围
        m_startDateEdit->hide();
        m_endDateEdit->hide();
    }
    
    emitSearchCriteriaChanged();
}

void OrderControlWidget::onStartPreparingClicked()
{
    if (!m_hasCurrentOrder) {
        QMessageBox::warning(this, "提示", "请先选择一个订单");
        return;
    }
    
    if (m_currentOrder.status != OrderStatus::PENDING) {
        QMessageBox::warning(this, "提示", "只有待处理状态的订单才能开始制作");
        return;
    }
    
    int ret = QMessageBox::question(this, "确认操作", 
                                   QString("确定要开始制作订单 %1 吗？").arg(m_currentOrder.id),
                                   QMessageBox::Yes | QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        emit statusChangeRequested(m_currentOrder.id, OrderStatus::PREPARING);
    }
}

void OrderControlWidget::onCompleteOrderClicked()
{
    if (!m_hasCurrentOrder) {
        QMessageBox::warning(this, "提示", "请先选择一个订单");
        return;
    }
    
    if (m_currentOrder.status != OrderStatus::PREPARING) {
        QMessageBox::warning(this, "提示", "只有制作中状态的订单才能完成");
        return;
    }
    
    int ret = QMessageBox::question(this, "确认操作", 
                                   QString("确定要完成订单 %1 吗？").arg(m_currentOrder.id),
                                   QMessageBox::Yes | QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        emit statusChangeRequested(m_currentOrder.id, OrderStatus::COMPLETED);
    }
}

void OrderControlWidget::onCancelOrderClicked()
{
    if (!m_hasCurrentOrder) {
        QMessageBox::warning(this, "提示", "请先选择一个订单");
        return;
    }
    
    if (m_currentOrder.status != OrderStatus::PENDING) {
        QMessageBox::warning(this, "提示", "只有待处理状态的订单才能取消");
        return;
    }
    
    int ret = QMessageBox::question(this, "确认操作", 
                                   QString("确定要取消订单 %1 吗？\n取消后无法恢复！").arg(m_currentOrder.id),
                                   QMessageBox::Yes | QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        emit statusChangeRequested(m_currentOrder.id, OrderStatus::CANCELLED);
    }
}

void OrderControlWidget::onRefreshClicked()
{
    emit refreshRequested();
    
    // 临时禁用刷新按钮，防止频繁点击
    m_refreshButton->setEnabled(false);
    QTimer::singleShot(1000, [this]() {
        if (m_refreshButton) {
            m_refreshButton->setEnabled(true);
        }
    });
}

void OrderControlWidget::onExportClicked()
{
    // 导出功能暂时不实现，显示提示
    QMessageBox::information(this, "提示", "导出功能将在后续版本中提供");
    emit exportRequested();
}

void OrderControlWidget::onSearchDelayTimeout()
{
    emitSearchCriteriaChanged();
}

void OrderControlWidget::setupSearchArea()
{
    // 创建搜索组
    m_searchGroup = new QGroupBox("搜索和过滤", this);
    m_searchLayout = new QGridLayout(m_searchGroup);
    m_searchLayout->setContentsMargins(8, 16, 8, 8);
    m_searchLayout->setSpacing(6);
    
    // 搜索框
    m_searchLayout->addWidget(new QLabel("顾客名:"), 0, 0);
    m_searchLineEdit = new QLineEdit();
    m_searchLineEdit->setPlaceholderText("输入顾客用户名(如:sq123)");
    m_searchLineEdit->setMaximumWidth(200);
    m_searchLayout->addWidget(m_searchLineEdit, 0, 1);
    
    // 状态过滤
    m_searchLayout->addWidget(new QLabel("状态:"), 0, 2);
    m_statusFilterCombo = new QComboBox();
    m_statusFilterCombo->addItem("全部状态");
    m_statusFilterCombo->addItem("待处理");
    m_statusFilterCombo->addItem("制作中");
    m_statusFilterCombo->addItem("已完成");
    m_statusFilterCombo->addItem("已取消");
    m_statusFilterCombo->setMaximumWidth(100);
    m_searchLayout->addWidget(m_statusFilterCombo, 0, 3);
    
    // 时间范围
    m_searchLayout->addWidget(new QLabel("时间:"), 0, 4);
    m_dateRangeCombo = new QComboBox();
    m_dateRangeCombo->addItem("全部时间");
    m_dateRangeCombo->addItem("今天");
    m_dateRangeCombo->addItem("昨天");
    m_dateRangeCombo->addItem("最近7天");
    m_dateRangeCombo->addItem("本月");
    m_dateRangeCombo->addItem("自定义");
    m_dateRangeCombo->setMaximumWidth(100);
    m_searchLayout->addWidget(m_dateRangeCombo, 0, 5);
    
    // 自定义日期范围（初始隐藏）
    m_startDateEdit = new QDateEdit();
    m_startDateEdit->setDate(QDate::currentDate().addDays(-7));
    m_startDateEdit->setMaximumWidth(100);
    m_startDateEdit->hide();
    m_searchLayout->addWidget(m_startDateEdit, 1, 4);
    
    m_endDateEdit = new QDateEdit();
    m_endDateEdit->setDate(QDate::currentDate());
    m_endDateEdit->setMaximumWidth(100);
    m_endDateEdit->hide();
    m_searchLayout->addWidget(m_endDateEdit, 1, 5);
    
    // 搜索状态标签
    m_searchStatusLabel = new QLabel();
    m_searchStatusLabel->setStyleSheet("color: #666666; font-size: 10px;");
    m_searchLayout->addWidget(m_searchStatusLabel, 1, 0, 1, 3);
    
    // 连接信号
    connect(m_searchLineEdit, &QLineEdit::textChanged,
            this, &OrderControlWidget::onSearchTextChanged);
    connect(m_statusFilterCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &OrderControlWidget::onStatusFilterChanged);
    connect(m_dateRangeCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &OrderControlWidget::onDateRangeChanged);
    connect(m_startDateEdit, &QDateEdit::dateChanged,
            this, &OrderControlWidget::onDateRangeChanged);
    connect(m_endDateEdit, &QDateEdit::dateChanged,
            this, &OrderControlWidget::onDateRangeChanged);
}

void OrderControlWidget::setupActionArea()
{
    // 创建操作组
    m_actionGroup = new QGroupBox("订单操作", this);
    m_actionLayout = new QHBoxLayout(m_actionGroup);
    m_actionLayout->setContentsMargins(8, 16, 8, 8);
    m_actionLayout->setSpacing(8);
    
    // 状态操作按钮
    m_startPreparingButton = new QPushButton("开始制作");
    m_startPreparingButton->setMinimumWidth(80);
    m_startPreparingButton->setStyleSheet(R"(
        QPushButton {
            background-color: #2196F3;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 6px 12px;
            font-weight: bold;
        }
        QPushButton:hover {
            background-color: #1976D2;
        }
        QPushButton:disabled {
            background-color: #CCCCCC;
            color: #666666;
        }
    )");
    
    m_completeOrderButton = new QPushButton("完成订单");
    m_completeOrderButton->setMinimumWidth(80);
    m_completeOrderButton->setStyleSheet(R"(
        QPushButton {
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 6px 12px;
            font-weight: bold;
        }
        QPushButton:hover {
            background-color: #388E3C;
        }
        QPushButton:disabled {
            background-color: #CCCCCC;
            color: #666666;
        }
    )");
    
    m_cancelOrderButton = new QPushButton("取消订单");
    m_cancelOrderButton->setMinimumWidth(80);
    m_cancelOrderButton->setStyleSheet(R"(
        QPushButton {
            background-color: #F44336;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 6px 12px;
            font-weight: bold;
        }
        QPushButton:hover {
            background-color: #D32F2F;
        }
        QPushButton:disabled {
            background-color: #CCCCCC;
            color: #666666;
        }
    )");
    
    m_deleteOrderButton = new QPushButton("删除订单");
    m_deleteOrderButton->setMinimumWidth(80);
    m_deleteOrderButton->setStyleSheet(R"(
        QPushButton {
            background-color: #9C27B0;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 6px 12px;
            font-weight: bold;
        }
        QPushButton:hover {
            background-color: #7B1FA2;
        }
        QPushButton:disabled {
            background-color: #CCCCCC;
            color: #666666;
        }
    )");
    
    // 功能按钮
    m_refreshButton = new QPushButton("刷新");
    m_refreshButton->setMinimumWidth(60);
    
    m_exportButton = new QPushButton("导出");
    m_exportButton->setMinimumWidth(60);
    
    // 添加到布局
    m_actionLayout->addWidget(m_startPreparingButton);
    m_actionLayout->addWidget(m_completeOrderButton);
    m_actionLayout->addWidget(m_cancelOrderButton);
    m_actionLayout->addWidget(m_deleteOrderButton);
    m_actionLayout->addStretch();
    m_actionLayout->addWidget(m_refreshButton);
    m_actionLayout->addWidget(m_exportButton);
    
    // 连接信号
    connect(m_startPreparingButton, &QPushButton::clicked,
            this, &OrderControlWidget::onStartPreparingClicked);
    connect(m_completeOrderButton, &QPushButton::clicked,
            this, &OrderControlWidget::onCompleteOrderClicked);
    connect(m_cancelOrderButton, &QPushButton::clicked,
            this, &OrderControlWidget::onCancelOrderClicked);
    connect(m_deleteOrderButton, &QPushButton::clicked,
            this, &OrderControlWidget::onDeleteOrderClicked);
    connect(m_refreshButton, &QPushButton::clicked,
            this, &OrderControlWidget::onRefreshClicked);
    connect(m_exportButton, &QPushButton::clicked,
            this, &OrderControlWidget::onExportClicked);
    
    // 创建主布局
    if (!m_mainLayout) {
        m_mainLayout = new QVBoxLayout(this);
        m_mainLayout->setContentsMargins(0, 0, 0, 0);
        m_mainLayout->setSpacing(8);
    }
    
    m_mainLayout->addWidget(m_searchGroup);
    m_mainLayout->addWidget(m_actionGroup);
    
    // 设置整体样式
    setStyleSheet(R"(
        QGroupBox {
            font-weight: bold;
            font-size: 11px;
            border: 1px solid #D0D0D0;
            border-radius: 4px;
            margin-top: 8px;
            padding-top: 4px;
        }
        
        QGroupBox::title {
            subcontrol-origin: margin;
            left: 8px;
            padding: 0 4px 0 4px;
            background-color: white;
        }
        
        QLabel {
            font-size: 11px;
            font-weight: normal;
        }
        
        QLineEdit, QComboBox, QDateEdit {
            border: 1px solid #D0D0D0;
            border-radius: 3px;
            padding: 4px;
            font-size: 11px;
            height: 20px;
        }
        
        QLineEdit:focus, QComboBox:focus, QDateEdit:focus {
            border-color: #2196F3;
        }
        
        QPushButton {
            border: 1px solid #D0D0D0;
            border-radius: 3px;
            padding: 4px 8px;
            font-size: 11px;
            background-color: #F5F5F5;
            min-height: 20px;
        }
        
        QPushButton:hover {
            background-color: #E0E0E0;
        }
        
        QPushButton:pressed {
            background-color: #D0D0D0;
        }
    )");
}

void OrderControlWidget::updateActionButtons()
{
    if (!m_hasCurrentOrder) {
        // 没有选中订单，禁用所有状态操作按钮
        m_startPreparingButton->setEnabled(false);
        m_completeOrderButton->setEnabled(false);
        m_cancelOrderButton->setEnabled(false);
        m_deleteOrderButton->setEnabled(false);
        return;
    }
    
    // 根据当前订单状态启用相应按钮
    OrderStatus status = m_currentOrder.status;
    
    m_startPreparingButton->setEnabled(status == OrderStatus::PENDING);
    m_completeOrderButton->setEnabled(status == OrderStatus::PREPARING);
    m_cancelOrderButton->setEnabled(status == OrderStatus::PENDING);
    
    // 只能删除已完成或已取消的订单
    m_deleteOrderButton->setEnabled(status == OrderStatus::COMPLETED || 
                                    status == OrderStatus::CANCELLED);
}

OrderSearchCriteria OrderControlWidget::buildSearchCriteria()
{
    OrderSearchCriteria criteria;
    
    // 顾客名搜索
    criteria.customerName = m_searchLineEdit->text().trimmed();
    
    // 状态过滤
    int statusIndex = m_statusFilterCombo->currentIndex();
    if (statusIndex > 0) {
        criteria.status = static_cast<OrderStatus>(statusIndex - 1);
    } else {
        criteria.status = static_cast<OrderStatus>(-1); // 全部状态
    }
    
    // 时间范围
    int rangeIndex = m_dateRangeCombo->currentIndex();
    QPair<QDateTime, QDateTime> dateRange = getDateRange(rangeIndex);
    criteria.startDate = dateRange.first;
    criteria.endDate = dateRange.second;
    
    return criteria;
}

void OrderControlWidget::emitSearchCriteriaChanged()
{
    OrderSearchCriteria criteria = buildSearchCriteria();
    m_currentCriteria = criteria;
    
    // 更新搜索状态显示
    QString statusText;
    if (criteria.hasFilters()) {
        QStringList filters;
        if (!criteria.customerName.isEmpty()) {
            filters << QString("顾客名: %1").arg(criteria.customerName);
        }
        if (criteria.status != static_cast<OrderStatus>(-1)) {
            filters << QString("状态: %1").arg(m_statusFilterCombo->currentText());
        }
        if (criteria.startDate.isValid() || criteria.endDate.isValid()) {
            filters << QString("时间: %1").arg(m_dateRangeCombo->currentText());
        }
        statusText = "已应用过滤器: " + filters.join(", ");
    } else {
        statusText = "显示全部订单";
    }
    
    m_searchStatusLabel->setText(statusText);
    
    emit searchCriteriaChanged(criteria);
}

QPair<QDateTime, QDateTime> OrderControlWidget::getDateRange(int rangeIndex)
{
    QDateTime startDate, endDate;
    QDate today = QDate::currentDate();
    
    switch (rangeIndex) {
        case 1: // 今天
            startDate = QDateTime(today, QTime(0, 0, 0));
            endDate = QDateTime(today, QTime(23, 59, 59));
            break;
            
        case 2: // 昨天
            {
                QDate yesterday = today.addDays(-1);
                startDate = QDateTime(yesterday, QTime(0, 0, 0));
                endDate = QDateTime(yesterday, QTime(23, 59, 59));
            }
            break;
            
        case 3: // 最近7天
            startDate = QDateTime(today.addDays(-6), QTime(0, 0, 0));
            endDate = QDateTime(today, QTime(23, 59, 59));
            break;
            
        case 4: // 本月
            {
                QDate firstDayOfMonth(today.year(), today.month(), 1);
                startDate = QDateTime(firstDayOfMonth, QTime(0, 0, 0));
                endDate = QDateTime(today, QTime(23, 59, 59));
            }
            break;
            
        case 5: // 自定义
            startDate = QDateTime(m_startDateEdit->date(), QTime(0, 0, 0));
            endDate = QDateTime(m_endDateEdit->date(), QTime(23, 59, 59));
            break;
            
        default: // 全部时间
            // 不设置日期范围
            break;
    }
    
    return qMakePair(startDate, endDate);
}

void OrderControlWidget::onDeleteOrderClicked()
{
    if (!m_hasCurrentOrder) {
        return;
    }
    
    // 检查订单状态是否允许删除
    if (m_currentOrder.status != OrderStatus::COMPLETED && 
        m_currentOrder.status != OrderStatus::CANCELLED) {
        QMessageBox::warning(this, "删除订单", 
            "只能删除已完成或已取消的订单！");
        return;
    }
    
    // 确认删除
    int ret = QMessageBox::question(this, "确认删除", 
        QString("确定要删除订单 %1 吗？\n\n此操作不可撤销！").arg(m_currentOrder.id),
        QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        // 发射删除请求信号
        emit deleteOrderRequested(m_currentOrder.id);
    }
}
